/* eslint-disable no-unused-vars */
'use strict';
const path = require('path');
const Service = require('egg').Service;
const uuidv1 = require('uuid').v1;

class HtmlToPDFService extends Service {

  // async test(payload) {
  //   const { ctx } = this;
  //   const { url } = payload;
  //   console.log("========================= test ==============================");
  //   console.log(url);
  //   const launchOptions = {
  //     headless: true,
  //     args: [ '--no-sandbox', '--disable-dev-shm-usage' ],
  //     executablePath: path.join(__dirname, '../../node_modules/puppeteer/.local-chromium/linux-938248/chrome-linux/chrome'),
  //   };

  //   const browser = await puppeteer.launch(launchOptions);
  //   const page = await browser.newPage();
  //   await page.goto(url);
  //   await page.pdf({ path: path.join(__dirname, '../public/pdf/测试.pdf') });
  //   const pdfBase64String = await ctx.helper.base64_encode(path.join(__dirname, '../public/pdf/测试.pdf'));
  //   await browser.close();
  //   console.log("========================= test over ==============================");
  //   console.log(pdfBase64String);
  //   return { pdfBase64String };
  // }

  async index(payload) {
    const { url } = payload;

    let errInfo = null;
    const  uuid = uuidv1();
    const pdfPath = path.join(__dirname, '/../public/pdf/' + uuid + '.pdf');

    const launchOptions = {
      headless: true,
      args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage' ],
      executablePath: '/root/package_puppeteer/puppeteer/.local-chromium/linux-938248/chrome-linux/chrome',
    };

    try {
      // puppeteer.launch(launchOptions).then(async browser => {
      //   const page = await browser.newPage();
      //   await page.goto('http://www.baidu.com');
      //   await page.screenshot({path: path.join(__dirname, '../public/screenshot.png')});
      //   await browser.close();
      // });

      const puppeteer = require('puppeteer');

      puppeteer.launch(launchOptions).then(async browser => {
        const page = await browser.newPage();
        await page.goto(url);
        // await page.screenshot({ path: path.join(__dirname, '../public/screenshot.png') });
        await page.pdf({ path: pdfPath });
        await browser.close();
      });
  
      // const browser = await puppeteer.launch(launchOptions);
      // const page = await browser.newPage();
      // await page.goto(url);
      // // await page.screenshot({ path: path.join(__dirname, '../public/pdf/screenshot.png') });
      // await browser.close();

    } catch (error) {
      errInfo = error.toString();
    }
   
    return { a: "接口返回了", url, launchOptions, errInfo };
  }

  async index2(payload) {
    const { ctx } = this;
    const { url, waitFor, top, bottom, left, right, headerTemplate, footerTemplate, isLandscape } = payload;
    let browser;
    let res;
    let uuid = '';

    if (!url) {
      ctx.throw(404, 'url not found');
    }

    const launchOptions = {
      headless: true,
      args: [ '--no-sandbox', '--disable-dev-shm-usage' ],
      executablePath: '/root/package_puppeteer/puppeteer/.local-chromium/linux-938248/chrome-linux/chrome',
    };

    await (async () => {
      browser = await puppeteer.launch(launchOptions);
      const page = await browser.newPage();
      await page.goto(url);

      if (waitFor) {
        await page.waitFor(waitFor);
      }

      uuid = uuidv1();
      const mytop = top ? Number(top) : 0;
      const mybottom = bottom ? Number(bottom) : 0;
      const myleft = left ? Number(left) : 0;
      const myright = right ? Number(right) : 0;
      const myheaderTemplate = headerTemplate ? headerTemplate : '<span></span>';
      const myfooterTemplate = footerTemplate ? footerTemplate : '<span></span>';
      const landscape = isLandscape === '1';

      await page.pdf({ path: path.join(__dirname, '/../public/pdf/' + uuid + '.pdf'), margin: { top: mytop, bottom: mybottom, left: myleft, right: myright }, printBackground: true, landscape, format: 'A4', displayHeaderFooter: true, headerTemplate: myheaderTemplate, footerTemplate: myfooterTemplate });
      const pdfBase64String = await ctx.helper.base64_encode(path.join(__dirname, '/../public/pdf/' + uuid + '.pdf'));
      // await ctx.helper.deleteFile(path.join(__dirname, '/../public/pdf/' + uuid + '.pdf'));
      res = { pdfBase64String };
      if (browser) {
        await browser.close();
      }
    })().catch(
      async err => {
        const statResult = await ctx.helper.stat(path.join(__dirname, '/../public/pdf/' + uuid + '.pdf'));
        if (statResult) {
          await ctx.helper.deleteFile(path.join(__dirname, '/../public/pdf/' + uuid + '.pdf'));
        }
        if (browser) {
          await browser.close();
        }
        ctx.throw(500, err);
      }
    );
    return res;
  }
}

module.exports = HtmlToPDFService;
